define(['mui','validator', 'validator-lang'], function ($, Validator, undefined) {
    var Form = {
        config: {
            fieldlisttpl: '<dd class="form-inline"><input type="text" name="<%=name%>[<%=index%>][key]" class="form-control" value="<%=row.key%>" size="10" /> <input type="text" name="<%=name%>[<%=index%>][value]" class="form-control" value="<%=row.value%>" /> <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span> <span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span></dd>'
        },
        events: {
            validator: function (form, success, error, submit) {
                if (!form.is("form"))
                    return;
                //绑定表单事件
                form.validator($.extend({
                    display: function (elem) {
                         var tips = ($(elem).attr('placeholder'));
                        showTips(tips);
                    },

                    valid: function (ret) {
                        var that = this, submitBtn = $(".layer-footer [type=submit]", form);
                        that.holdSubmit(true);
                        submitBtn.addClass("disabled");
                        //验证通过提交表单
                        var submitResult = Form.api.submit($(ret), function (data, ret) {
                            that.holdSubmit(false);
                            submitBtn.removeClass("disabled");
                            if (false === $(this).triggerHandler("success.form", [data, ret])) {
                                return false;
                            }
                            if (typeof success === 'function') {
                                if (false === success.call($(this), data, ret)) {
                                    return false;
                                }
                            }
                            //提示及关闭当前窗口
                            var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
                            parent.Toastr.success(msg);
                            parent.$(".btn-refresh").trigger("click");
                            var index = parent.Layer.getFrameIndex(window.name);
                            parent.Layer.close(index);
                            return false;
                        }, function (data, ret) {
                            that.holdSubmit(false);
                            if (false === $(this).triggerHandler("error.form", [data, ret])) {
                                return false;
                            }
                            submitBtn.removeClass("disabled");
                            if (typeof error === 'function') {
                                if (false === error.call($(this), data, ret)) {
                                    return false;
                                }
                            }
                        }, submit);
                        //如果提交失败则释放锁定
                        if (!submitResult) {
                            that.holdSubmit(false);
                            submitBtn.removeClass("disabled");
                        }
                        return false;
                    }
                }, form.data("validator-options") || {}));

                //移除提交按钮的disabled类
                $(".layer-footer [type=submit],.fixed-footer [type=submit],.normal-footer [type=submit]", form).removeClass("disabled");
                //自定义关闭按钮事件
                form.on("click", ".layer-close", function () {
                    var index = parent.Layer.getFrameIndex(window.name);
                    parent.Layer.close(index);
                    return false;
                });
            },
            submit: function(form,disabled){
                var that = this, submitBtn = $('#formSubmitBtn');
                $('#formSubmitBtn').click(function () {
                    Weui.form.validate(form, function (error) {
                        console.log(error);
                        if (!error) {
                            if(disabled)
                            {
                                $("#formSubmitBtn").attr("disabled", true);
                                $("#formSubmitBtn").addClass("weui-btn_disabled");
                            }
                            $.ajax({
                            //几个参数需要注意一下
                                type: "POST",//方法类型
                                dataType: "json",//预期服务器返回的数据类型
                                url: location.href,//url
                                data: form.serialize(),
                                success: function (ret) {

                                    $.alert({
                                        title: ret.msg,
                                        // text: '<a href="http://news.qau.edu.cn/channel/yqzty"><img src="/assets/img/yqbt2.jpg" width="100%" /></a>',
                                        onOK: function () {
                                            if(ret.code == 1)
                                            {
                                                if(ret.url)
                                                    window.location.href=ret.url;
                                                else
                                                    window.history.back()
                                            }
                                            if(ret.code == 0)
                                            {
                                                $("#formSubmitBtn").attr("disabled", false);
                                                $("#formSubmitBtn").removeClass("weui-btn_disabled");
                                            }

                                        }
                                    });
                                },
                                error : function(error) {
                                    $("#formSubmitBtn").attr("disabled", false);
                                    $("#formSubmitBtn").removeClass("weui-btn_disabled");
                                }
                            });

                        }

                    }, {
                     regexp: {
                         IDNUM: /(?:^\d{15}$)|(?:^\d{18}$)|^\d{17}[\dXx]$/,
                         VCODE: /^.{4}$/,
                         MOBILE: /(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/,
                     }
                 });
                    return false;
                });

            },
            record: function(form) {
                var that = this, submitBtn = $('#formRecordBtn');
                submitBtn.click(function () {

                    Weui.form.validate(form, function (error) {

                        if (!error) {
                            Form.api.savestorage(form,'record');
                            $.ajax({
                            //几个参数需要注意一下
                                type: "POST",//方法类型
                                dataType: "json",//预期服务器返回的数据类型
                                url: location.href,//url
                                data: form.serialize(),
                                success: function (ret) {
                                     $.alert({
                                        title: ret.msg,
                                        text: ret.data.nickname + '您好:<br>您扫码时间为：' + ret.data.create_time ,
                                        onOK: function () {
                                            WeixinJSBridge.invoke('closeWindow', {}, function (res) {
                                            });

                                        }
                                    });
                                    GetTime();

                                },
                                error : function(error) {
                                    $.alert({
                                        title: '提示',
                                        text: '网络异常,请再次提交！',
                                        onOK: function () {
                                            // WeixinJSBridge.invoke('closeWindow', {}, function (res) { });
                                        }
                                    });
                                }
                            });

                        }

                    }, {
                     regexp: {
                         IDNUM: /(?:^\d{15}$)|(?:^\d{18}$)|^\d{17}[\dXx]$/,
                         VCODE: /^.{4}$/,
                         MOBILE: /(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/,
                     }
                 });
                    return false;
                });
            },
            draf: function(form) {
                var that = this, submitBtn = $('#formDraftBtn');
                $('#formDraftBtn').click(function () {
                    // $form.find('[required]');
                    if(!$("#name").val()){
                        error = { ele: $("#name")[0], msg: 'empty' };
                        Weui.form.showErrorTips(error);
                        return false;
                    }

                    console.log(form.serialize());
                    $.ajax({
                    //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: location.href,//url
                        data: form.serialize()+'&row[is_check]=-1',
                        success: function (ret) {

                            $.alert({
                                title: ret.msg,
                                // text: '<a href="http://news.qau.edu.cn/channel/yqzty"><img src="/assets/img/yqbt2.jpg" width="100%" /></a>',
                                onOK: function () {

                                    // if(ret.code == 1)
                                    // {
                                    //     WeixinJSBridge.invoke('closeWindow', {}, function (res) { });
                                    // }
                                    // if(ret.code == 0 && ret.url)
                                    // {
                                        window.location.href=ret.url;
                                    // }
                                }
                            });
                            // if(ret.code == 1)
                            //
                        },
                        error : function(error) {
                            // console.log(error);
                            $.alert({
                                title: '提示',
                                text: '网络异常,请再次提交！',
                                onOK: function () {
                                    // WeixinJSBridge.invoke('closeWindow', {}, function (res) { });
                                }
                            });
                            // alert("异常！");
                        }
                    }, {
                        regexp: {
                            IDNUM: /(?:^\d{15}$)|(?:^\d{18}$)|^\d{17}[\dXx]$/,
                            VCODE: /^.{4}$/,
                            TEL: /^[1][3,4,5,7,8][0-9]{9}$/
                        }
                    });


                    return false;
                });
            },

            calendar: function() {
                // $(".calendar").onfocus();
                $(".calendar").calendar({dateFormat: 'yyyy-mm-dd'});
            },

            upload: function() {
                var allowTypes = [ 'image/jpg', 'image/jpeg', 'image/png', 'image/gif' ];
                // 1024KB，也就是 1MB
                var maxSize = 1024 * 1024;
                // 图片最大宽度
                var maxWidth = 800;
                var maxHeight = 800;
                // 最大上传图片数量
                var maxCount = 6;

                var tmpl = '<li class="weui-uploader__file weui-uploader__file_status" id="#ImgID#" style="background-image:url(#url#)"> <div class="weui-uploader__file-content"></div></li>',
                    $gallery = $("#gallery"),
                    $galleryImg = $("#galleryImg"),
                    $uploaderInput = $(".pupload"),
                    $uploaderFiles = $("#uploaderFiles"),
                    $galleryDelete=$(".weui-gallery__opr"),
                    $previewer=$(".previewer"),
                    element = $(".pupload");

                var u = navigator.userAgent;
                if(u.indexOf('Android') > -1 || u.indexOf('Adr') > -1)
                {

                    $("#uploaderInput").attr('capture','camera');
                }
                element.each(function () {
                    var that = this;
                    var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
                    var preview_id = $(that).data("preview-id") ? $(that).data("preview-id") : "";
                    var multiple = $(that).attr('multiple');

                    $(this).on("change", function(event){
                        var src, url = window.URL || window.webkitURL || window.mozURL, files = event.target.files;
                        if (files.length === 0) {
                            return;
                        }
                        for (var i = 0, len = files.length; i < len; ++i) {
                            var fd = new FormData();
                            fd.append('file', files[i]);
                            $.ajax({
                                url:'/wap/ajax/upload',
                                type:'POST',
                                data:fd,
                                processData:false,  //tell jQuery not to process the data
                                contentType: false,  //tell jQuery not to set contentType
                                //这儿的三个参数其实就是XMLHttpRequest里面带的信息。
                                success:function (ret) {
                                    if(ret.code == 1 )
                                    {
                                        var data = typeof ret.data !== 'undefined' ? ret.data : null;
                                        if (input_id) {
                                            var urlArr = [];
                                            var inputObj = $("#" + input_id);
                                            if (multiple && inputObj.val() !== "") {
                                                console.log(inputObj.val())
                                                urlArr.push(inputObj.val());
                                            }
                                            urlArr.push(data.url);
                                            console.log(urlArr);
                                            // inputObj.val(urlArr.join(","));
                                            inputObj.val(urlArr.join(",")).trigger("change");
                                        }
                                    }
                                }
                            })
                        }
                    })


                    if (preview_id && input_id) {
                        $(document.body).on("keyup change", "#" + input_id, function (e) {
                            var inputStr = $("#" + input_id).val();
                            var inputArr = inputStr.split(/\,/);
                            $("#" + preview_id).empty();
                            var tpl = $("#" + preview_id).data("template") ? $("#" + preview_id).data("template") : "";

                            $.each(inputArr, function (i, j) {
                                if (!j) {
                                    return true;
                                }
                                // var suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(j);
                                // suffix = suffix ? suffix[1] : 'file';
                                // var data = {url: j, fullurl: Fast.api.cdnurl(j), data: $(that).data(), key: i, index: i, value: (json && typeof json[i] !== 'undefined' ? json[i] : null), suffix: suffix};
                                // var html = tpl ? Template(tpl, data) : Template.render(Upload.config.previewtpl, data);
                                var html = $('<li class="weui-uploader__file" data-url="'+j+'"  id="ImgID" style="background-image:url(' + j + ')"></li>');

                                $("#" + preview_id).append(html);
                            });
                        });
                        $("#" + input_id).trigger("change");
                    }
                    if (preview_id) {

                        // 监听事件
                        $(document.body).on("fa.preview.change", "#" + preview_id, function () {
                            var urlArr = [];
                            $("#" + preview_id + " [data-url]").each(function (i, j) {
                                urlArr.push($(this).data("url"));
                            });
                            if (input_id) {
                                $("#" + input_id).val(urlArr.join(","));
                            }
                            // refresh($("#" + preview_id).data("name"));
                        });

                        $("#"+preview_id).on("click", "li", function(){
                            index = $(this).index();

                            $galleryImg.data("preview_id", preview_id);
                            $galleryImg.data("li_index", index);

                            $galleryImg.attr("style", this.getAttribute("style"));
                            $galleryDelete.show();
                            $gallery.fadeIn(100);
                        });
                    }


                })
                $(".weui-gallery__del").click(function() {
                    var pre_id = $galleryImg.data("preview_id");
                    var index = $galleryImg.data("li_index")
                    // console.log(index)
                    $('#'+pre_id+' li').eq(index).remove()
                    $("#" + pre_id).trigger("fa.preview.change");
                    // console.log($galleryImg.data("preview_id"));
                })



                var index;

                $previewer.on("click", "li", function(){
                    index = $(this).index();
                    $galleryImg.attr("style", this.getAttribute("style"));
                    $galleryDelete.hide();
                    $gallery.fadeIn(100);
                });

                $gallery.on("click", function(){
                    $gallery.fadeOut(100);
                });
            }
        },
        api: {
            bindevent: function (form,disabled) {
                $("input,textarea").on("blur",function(){
                    setTimeout(function(){
                        window.scrollTo(0,0);
                    },100)
                }).on('focus',function(){
                    var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                    var offsetTop = $(this).offset().top - (clientHeight / 4);
                    setTimeout(function(){
                        window.scrollTo(0,offsetTop);
                    },100)
                })
                form = typeof form === 'object' ? form : $(form);

                var events = Form.events;

                events.submit(form,disabled);
                events.draf(form);
                events.record(form);
                events.calendar(form);
                events.upload(form);
            },
            savestorage: function(form,storagename) {
                var formid = form.attr('id')
                console.log(formid);
                var history=[];
                var input_arr = ['text','tel','hidden','number','password'];
                window.localStorage[storagename]='';


                window.localStorage[storagename]='';
                $("#"+formid+" input").each(function(index, element) {
                    var item_type = element.type;
                    var item_id = element.id
                    var item_name = element.name;
                    var item_value = element.value;

                    if(input_arr.indexOf(item_type) > -1){
                         history.push({name:item_name,id:item_id,type:item_type,value:item_value});
                    }
                    if(item_type =='radio'){

                        var checked = element.checked;
                        if(checked)
                        {
                            history.push({name:item_name,id:item_id,type:item_type,value:item_value});
                        }
                            
                    }
                });
                $("#"+formid+" textarea").each(function(index, element) {
                    var item_type = 'textarea';
                    var item_id = element.id
                    var item_name = element.name;
                    var item_value = element.value;
                              
                    history.push({name:item_name,id:item_id,type:item_type,value:item_value});  
                });
                console.log(history);
                 window.localStorage[storagename]=JSON.stringify(history)
            },
            getstorage:function(storagename) {
                 var localMsg ;

                if(window.localStorage[storagename]){
                    localMsg=JSON.parse(window.localStorage[storagename]);
                }
                // console.log(inputMsg);
                console.log(localMsg)
                var input_arr = ['text','tel','hidden','number','password','textarea'];
                if(localMsg && localMsg.length > -1){
                    for(var i=0;i<localMsg.length;i++){
                        var item_id = localMsg[i].id;
                        var item_name = localMsg[i].name;
                        var item_type = localMsg[i].type;
                        var item_value = localMsg[i].value;

                        var dom = item_id ? $("#"+item_id) : $("[name='"+item_name+"']");

                        if(input_arr.indexOf(item_type) > -1){
                            dom.val(item_value);
                        }
                        if(item_type =='radio'){
                            if(input_radio_arr.indexOf(item_name) == -1)
                            {
                                if(item_id)
                                    dom.prop('checked',true);
                                else
                                    $("input:radio[name='"+item_name+"'][value='" +item_value+ "']").prop("checked",true);
                            }
                        }

                    }

                }
            },
            getLocation:function() {
                if (navigator.geolocation){
                    navigator.geolocation.getCurrentPosition(
                        function(ev){
                            console.log(ev)
                            // alert(ev.coords.latitude + " : " + ev.coords.longitude);
                            $("#lat").val(ev.coords.latitude);
                            $("#lon").val(ev.coords.longitude);
                        },
                        function(err){
                            // alert(err.code+':'+err.message);
                        }, {
                          enableHighAcuracy: false, //位置是否精确获取
                          timeout: 5000,            //获取位置允许的最长时间
                          maximumAge: 1000          //多久更新获取一次位置
                        })
                }else{
                }
            },
            custom: {}
        },
    };
    return Form;
});